/************************************************************************
**
** 作者：许振坪
** 日期：2017-05-03
** 博客：http://blog.csdn.net/benkaoya
** 描述：读取IPC音视频流数据示例代码
**
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "./comm/onvif_comm.h"
#include "./comm/onvif_dump.h"

/************************************************************************
**函数：ONVIF_GetVideoEncoderConfigurationOptions
**功能：获取指定视频编码器配置的参数选项集
**参数：
        [in] MediaXAddr   - 媒体服务地址
        [in] ConfigurationToken - 视频编码器配置的令牌字符串，如果为NULL，则获取所有视频编码器配置的选项集（会杂在一起，
                                  无法区分选项集是归属哪个视频编码配置器的）
**返回：
        0表明成功，非0表明失败
**备注：
    1). 有两种方式可以获取指定视频编码器配置的参数选项集：一种是根据ConfigurationToken，另一种
        是根据ProfileToken
************************************************************************/
int ONVIF_GetVideoEncoderConfigurationOptions(const char *MediaXAddr, char *ConfigurationToken,struct soap *soap,struct _trt__GetVideoEncoderConfigurationOptionsResponse  &rep)
{
    int result = 0;

    struct _trt__GetVideoEncoderConfigurationOptions          req;

    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    req.ConfigurationToken = ConfigurationToken;

    ONVIF_SetAuthInfo(soap, username, passwd);
    result = soap_call___trt__GetVideoEncoderConfigurationOptions(soap, MediaXAddr, NULL, &req, &rep);

    SOAP_CHECK_ERROR(result, soap, "GetVideoEncoderConfigurationOptions");

    dump_trt__GetVideoEncoderConfigurationOptionsResponse(&rep);


EXIT:


    return result;
}

/************************************************************************
**函数：ONVIF_GetVideoEncoderConfiguration
**功能：获取设备上指定的视频编码器配置信息
**参数：
        [in] MediaXAddr - 媒体服务地址
        [in] ConfigurationToken - 视频编码器配置的令牌字符串
**返回：
        0表明成功，非0表明失败
**备注：
************************************************************************/
int ONVIF_GetVideoEncoderConfiguration(const char *MediaXAddr, char *ConfigurationToken,struct soap *soap,struct _trt__GetVideoEncoderConfigurationResponse  &rep)
{
    int result = 0;
    struct _trt__GetVideoEncoderConfiguration          req;

    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    ONVIF_SetAuthInfo(soap, username, passwd);

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    req.ConfigurationToken = ConfigurationToken;
    result = soap_call___trt__GetVideoEncoderConfiguration(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "GetVideoEncoderConfiguration");

    dump_trt__GetVideoEncoderConfigurationResponse(&rep);

EXIT:


    return result;
}

/************************************************************************
**函数：ONVIF_SetVideoEncoderConfiguration
**功能：修改指定的视频编码器配置信息
**参数：
        [in] MediaXAddr - 媒体服务地址
        [in] venc - 视频编码器配置信息
**返回：
        0表明成功，非0表明失败
**备注：
    1). 所设置的分辨率必须是GetVideoEncoderConfigurationOptions返回的“分辨率选项集”中的一种，
    否则调用SetVideoEncoderConfiguration会失败。
************************************************************************/
int ONVIF_SetVideoEncoderConfiguration(const char *MediaXAddr, tt__VideoEncoderConfiguration *config)
{
    int result = 0;
    struct soap *soap = NULL;

//    struct _trt__GetVideoEncoderConfiguration           gVECfg_req;
//    struct _trt__GetVideoEncoderConfigurationResponse   gVECfg_rep;

    struct _trt__SetVideoEncoderConfiguration           sVECfg_req;
    struct _trt__SetVideoEncoderConfigurationResponse   sVECfg_rep;

    SOAP_ASSERT(NULL != MediaXAddr);
    //SOAP_ASSERT(NULL != venc);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

//    memset(&gVECfg_req, 0x00, sizeof(gVECfg_req));
//    memset(&gVECfg_rep, 0x00, sizeof(gVECfg_rep));
//    gVECfg_req.ConfigurationToken = venc->token;

//    ONVIF_SetAuthInfo(soap, username, passwd);
//    result = soap_call___trt__GetVideoEncoderConfiguration(soap, MediaXAddr, NULL, &gVECfg_req, &gVECfg_rep);
//    SOAP_CHECK_ERROR(result, soap, "GetVideoEncoderConfiguration");

//    if (NULL == gVECfg_rep.Configuration) {
//        SOAP_DBGERR("video encoder configuration is NULL.\n");
//        goto EXIT;
//    }

    memset(&sVECfg_req, 0x00, sizeof(sVECfg_req));
    memset(&sVECfg_rep, 0x00, sizeof(sVECfg_rep));

    sVECfg_req.ForcePersistence = xsd__boolean__true_;
    sVECfg_req.Configuration    = config;

//    if (NULL != sVECfg_req.Configuration->Resolution) {
//        sVECfg_req.Configuration->Resolution->Width  = venc->Width;
//        sVECfg_req.Configuration->Resolution->Height = venc->Height;
//    }

    ONVIF_SetAuthInfo(soap, username, passwd);
    result = soap_call___trt__SetVideoEncoderConfiguration(soap, MediaXAddr, NULL, &sVECfg_req, &sVECfg_rep);
    SOAP_CHECK_ERROR(result, soap, "SetVideoEncoderConfiguration");

EXIT:

    if (SOAP_OK == result) {
        SOAP_DBGLOG("\nSetVideoEncoderConfiguration success!!!\n");
    }

    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }

    return result;
}
/************************************************************************
**函数：ONVIF_GetNetworkInterfaces
**功能：修改指定的视频编码器配置信息
**参数：
        [in] MediaXAddr - 媒体服务地址
        [in] rep - 网络接口信息
**返回：
        0表明成功，非0表明失败
**备注：

************************************************************************/
int ONVIF_GetNetworkInterfaces(const char *MediaXAddr,struct soap *soap,struct _tds__GetNetworkInterfacesResponse  &rep)
{
    int result = 0;
    struct _tds__GetNetworkInterfaces req;

    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    ONVIF_SetAuthInfo(soap, username, passwd);

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    //req._tds__GetNetworkIn = ConfigurationToken;
    result = soap_call___tds__GetNetworkInterfaces(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "GetNetworkInterfaces");

    dump_tds__GetNetworkInterfaces(&rep);

EXIT:

    return result;
}
int ONVIF_SetNetworkInterfaces(const char *MediaXAddr,struct _tds__SetNetworkInterfaces &req)
{
    int result = 0;
    struct soap *soap = NULL;
    struct _tds__SetNetworkInterfacesResponse  rep;


    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    ONVIF_SetAuthInfo(soap, username, passwd);


    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    //req._tds__GetNetworkIn = ConfigurationToken;
    result = soap_call___tds__SetNetworkInterfaces(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "SetNetworkInterfaces");

EXIT:

    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }
    return result;
}
int ONVIF_GetDeviceInformation(const char *MediaXAddr,struct soap *soap,struct _tds__GetDeviceInformationResponse  &rep)
{
    int result = 0;
    struct _tds__GetDeviceInformation req;

    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    //设置鉴权信息
    result = ONVIF_SetAuthInfo(soap, username, passwd);

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    //req._tds__GetNetworkIn = ConfigurationToken;
    result = soap_call___tds__GetDeviceInformation(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "GetDeviceInformation");

    dump_tds__GetDeviceInformationResponse(&rep);

EXIT:

    return result;
}
/************************************************************************
**函数：ONVIF_GetStreamUri
**功能：获取设备码流地址(RTSP)
**参数：
        [in]  MediaXAddr    - 媒体服务地址
        [in]  ProfileToken  - the media profile token
        [out] uri           - 返回的地址
        [in]  sizeuri       - 地址缓存大小
**返回：
        0表明成功，非0表明失败
**备注：
************************************************************************/
int ONVIF_GetStreamUri(const char *MediaXAddr, char *ProfileToken, char *uri, unsigned int sizeuri)
{
    int result = 0;
    struct soap *soap = NULL;
    struct tt__StreamSetup              ttStreamSetup;
    struct tt__Transport                ttTransport;
    struct _trt__GetStreamUri           req;
    struct _trt__GetStreamUriResponse   rep;

    SOAP_ASSERT(NULL != MediaXAddr);
    SOAP_ASSERT(NULL != uri);
    memset(uri, 0x00, sizeuri);

    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));
    memset(&ttStreamSetup, 0x00, sizeof(ttStreamSetup));
    memset(&ttTransport, 0x00, sizeof(ttTransport));
    ttStreamSetup.Stream                = tt__StreamType__RTP_Unicast;
    ttStreamSetup.Transport             = &ttTransport;
    ttStreamSetup.Transport->Protocol   = tt__TransportProtocol__RTSP;
    ttStreamSetup.Transport->Tunnel     = NULL;
    req.StreamSetup                     = &ttStreamSetup;
    req.ProfileToken                    = ProfileToken;

    ONVIF_SetAuthInfo(soap, username, passwd);
    result = soap_call___trt__GetStreamUri(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "GetServices");

    dump_trt__GetStreamUriResponse(&rep);

    result = -1;
    if (NULL != rep.MediaUri) {
        if (NULL != rep.MediaUri->Uri) {
            if (sizeuri > strlen(rep.MediaUri->Uri)) {
                strcpy(uri, rep.MediaUri->Uri);
                result = 0;
            } else {
                SOAP_DBGERR("Not enough cache!\n");
            }
        }
    }

EXIT:

    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }

    return result;
}


int ONVIF_GetStreamReplay(const char *MediaXAddr, char *ProfileToken)
{
    int result = 0;
    struct soap *soap = NULL;
    struct tt__StreamSetup              ttStreamSetup;
    struct tt__Transport                ttTransport;
    struct _trp__GetReplayUri           req;
    struct _trp__GetReplayUriResponse   rep;

    SOAP_ASSERT(NULL != MediaXAddr);

    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));

    memset(&req, 0x00, sizeof(req));
    memset(&rep, 0x00, sizeof(rep));

    req.RecordingToken = ProfileToken;

    ONVIF_SetAuthInfo(soap, username, passwd);

    result = soap_call___trp__GetReplayUri(soap, MediaXAddr, NULL, &req, &rep);
    SOAP_CHECK_ERROR(result, soap, "GetReplayUri");

    //dump_trt__GetStreamUriResponse(&rep);

    result = -1;
    if (NULL != rep.Uri) {

    }

EXIT:

    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }

    return result;
}
void cb_discovery(char *DeviceXAddr)
{
    char uri[ONVIF_ADDRESS_SIZE] = {0};                                         // 不带认证信息的URI地址
    char uri_auth[ONVIF_ADDRESS_SIZE + 50] = {0};                               // 带有认证信息的URI地址
    printf("0跳过，1继续：");
    int select=-1;
    scanf("%d",&select);
    if (select != 1)
    {
        return;
    }

    printf("Input username and passwd for the camera of XAddrs %s\n",DeviceXAddr);
    printf("username:");
    scanf("%s",&username);
    printf("passwd:");
    getchar();
    gets(passwd);
    int result;
    int stmno = 0;                                                              // 码流序号，0为主码流，1为辅码流
    int profile_cnt = 0;                                                        // 设备配置文件个数
    struct tagProfile *profiles = NULL;                                         // 设备配置文件列表
    struct tagCapabilities capa;                                                // 设备能力信息

    struct _trt__GetVideoEncoderConfigurationOptionsResponse  veco_rep;              //视频编码器参数选项集
    struct soap *veco_soap = NULL;

    struct _trt__GetVideoEncoderConfigurationResponse  vec_rep;              //视频编码器参数选项集
    struct soap *vec_soap = NULL;

    //获取设备信息
    struct _tds__GetDeviceInformationResponse  info_rep;
    struct soap *info_soap = NULL;
    result = ONVIF_GetDeviceInformation(DeviceXAddr,info_soap,info_rep);
    if (result != 0)
    {
        printf("ONVIF_GetDeviceInformation failed:%d\n",result);
        return;
    }

    ONVIF_GetCapabilities(DeviceXAddr, &capa);                                // 获取设备能力信息（获取媒体服务地址）

    //设置ip
    struct _tds__GetNetworkInterfacesResponse  net_rep;
    struct soap *net_soap = NULL;
    result = ONVIF_GetNetworkInterfaces(DeviceXAddr,net_soap,net_rep);
    struct _tds__SetNetworkInterfaces setNet;
    setNet.NetworkInterface = (tt__NetworkInterfaceSetConfiguration*)malloc(sizeof(tt__NetworkInterfaceSetConfiguration));
    printf("当前ip:%s\n",net_rep.NetworkInterfaces->IPv4->Config->Manual->Address);
    printf("set ip:");
    gets(net_rep.NetworkInterfaces->IPv4->Config->Manual->Address);

    struct _tds__SetNetworkInterfaces setInteface_req;
    struct tt__NetworkInterfaceSetConfiguration config;
    struct tt__IPv4NetworkInterfaceSetConfiguration ipv4;
    struct tt__PrefixedIPv4Address manual;


    manual.Address =net_rep.NetworkInterfaces->IPv4->Config->Manual->Address;
    manual.PrefixLength =net_rep.NetworkInterfaces->IPv4->Config->Manual->PrefixLength;

    ipv4.Manual=&manual;
    ipv4.DHCP = &net_rep.NetworkInterfaces->IPv4->Config->DHCP;
    ipv4.Enabled = &net_rep.NetworkInterfaces->IPv4->Enabled;
    ipv4.__sizeManual = net_rep.NetworkInterfaces->IPv4->Config->__sizeManual;

    config.IPv4=&ipv4;
    config.Enabled = &net_rep.NetworkInterfaces->IPv4->Enabled;
    //config.Extension = net_rep.NetworkInterfaces->Extension;
    //config.Link->
    setInteface_req.NetworkInterface=&config;
    setInteface_req.InterfaceToken = net_rep.NetworkInterfaces->token;

    result = ONVIF_SetNetworkInterfaces(DeviceXAddr,setInteface_req);
    if (result == 0)
    {
        printf("Set IP successfully\n");
    }
    struct _trt__GetProfilesResponse    rep;
    struct soap *soap = NULL;
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));
    profile_cnt = ONVIF_GetProfiles(DeviceXAddr, &profiles,&rep,soap);                // 获取媒体配置文件（主/辅码流配置信息）

    for (int i = 0;i < profile_cnt;i++)
    {
        printf("get uri form MediaXAddr:%s\n",capa.MediaXAddr);
        ONVIF_GetStreamUri(capa.MediaXAddr, profiles[i].token, uri, sizeof(uri)); // 获取RTSP地址
        make_uri_withauth(uri, username, passwd, uri_auth, sizeof(uri_auth)); // 生成带认证信息的URI（有的IPC要求认证）
        printf("media channel %d %dx%d uri_auth:%s\n",i, profiles[i].venc.Width,profiles[i].venc.Height,uri_auth);
    }

    if (profile_cnt > stmno) {

        struct tagVideoEncoderConfiguration venc;
        char *vencToken = profiles[stmno].venc.token;                           //获取一个码流的token
        printf("get vencToken=%s VideoEncoderConfiguration\n",vencToken);

        ONVIF_GetVideoEncoderConfigurationOptions(DeviceXAddr, vencToken,veco_soap,veco_rep);  // 获取该码流支持的视频编码器参数选项集
        int sizeResolutionsAvailable = veco_rep.Options->H264->__sizeResolutionsAvailable;
        tt__VideoResolution  *vr = veco_rep.Options->H264->ResolutionsAvailable;

        ONVIF_GetVideoEncoderConfiguration(DeviceXAddr, vencToken,vec_soap,vec_rep);         // 获取该码流当前的视频编码器参数
        tt__VideoEncoderConfiguration *config = vec_rep.Configuration;
        printf("%s,%s当前分辨率：Width %d,Height %d\n",info_rep.Manufacturer,info_rep.Model,vec_rep.Configuration->Resolution->Width,vec_rep.Configuration->Resolution->Height);
        printf("支持的分辨率：\n");
        for (int i = 0;i < sizeResolutionsAvailable;i++)
        {
            printf("%d:Width:%d,Height:%d\n",i,vr[i].Width,vr[i].Height);

        }
        printf("请选择编号，选择要设置的分辨率，其他编号则跳过：");
        select=-1;
        scanf("%d",&select);
        if (select < 0 || select >= sizeResolutionsAvailable)
        {
            printf("分辨率不更改\n");

        }
        else
        {
            config->Resolution = &vr[select];
        }
        printf("支持的帧率：%d-%d\n",veco_rep.Options->H264->FrameRateRange->Min,veco_rep.Options->H264->FrameRateRange->Max);
        printf("设置帧率，0跳过：");
        select=-1;
        scanf("%d",&select);
        if (select < veco_rep.Options->H264->FrameRateRange->Min || select > veco_rep.Options->H264->FrameRateRange->Max)
        {
            printf("帧率不更改\n");

        }
        else
        {
            config->RateControl->FrameRateLimit = select;
        }

        result = ONVIF_SetVideoEncoderConfiguration(DeviceXAddr, config);             // 设置该码流当前的视频编码器参数

        //result = ONVIF_GetVideoEncoderConfiguration(capa.MediaXAddr, vencToken);         // 观察是否修改成功
        if (result == 0)
        {
            printf("set succesfully\n");
        }
    }

    if (NULL != veco_soap) {
        ONVIF_soap_delete(veco_soap);
    }
    if (NULL != vec_soap) {
        ONVIF_soap_delete(vec_soap);
    }
    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }

    if (NULL != profiles) {
        free(profiles);
        profiles = NULL;
    }
}

void getmediainfo(char *DeviceXAddr)
{

    char uri[ONVIF_ADDRESS_SIZE] = {0};                                         // 不带认证信息的URI地址
    char uri_auth[ONVIF_ADDRESS_SIZE + 50] = {0};                               // 带有认证信息的URI地址
    //printf("Input username and passwd for the camera of XAddrs %s\n",DeviceXAddr);
    //printf("username:");
    memcpy(&username,"test123",strlen("test123"));
    memcpy(&passwd,"Labtest@123",strlen("Labtest@123"));
//    scanf("%s",&username);
//    printf("passwd:");
//    getchar();
//    gets(passwd);
    int result;
    int stmno = 0;                                                              // 码流序号，0为主码流，1为辅码流
    int profile_cnt = 0;                                                        // 设备配置文件个数
    struct tagProfile *profiles = NULL;                                         // 设备配置文件列表
    struct tagCapabilities capa;                                                // 设备能力信息

    struct _trt__GetVideoEncoderConfigurationOptionsResponse  veco_rep;              //视频编码器参数选项集
    struct soap *veco_soap = NULL;

    struct _trt__GetVideoEncoderConfigurationResponse  vec_rep;              //视频编码器参数选项集
    struct soap *vec_soap = NULL;

//    //获取设备信息
    printf("\n**************start**************\n");
    struct _tds__GetDeviceInformationResponse  info_rep;
    struct soap *info_soap = NULL;
    result = ONVIF_GetDeviceInformation(DeviceXAddr,info_soap,info_rep);
    if (result != 0)
    {
        printf("ONVIF_GetDeviceInformation failed:%d\n",result);
        return;
    }

    ONVIF_GetCapabilities(DeviceXAddr, &capa);                                // 获取设备能力信息（获取媒体服务地址）
    printf("\n***************end*************\n");

    struct _trt__GetProfilesResponse    rep;
    struct soap *soap = NULL;
    SOAP_ASSERT(NULL != (soap = ONVIF_soap_new(SOAP_SOCK_TIMEOUT)));
    profile_cnt = ONVIF_GetProfiles(DeviceXAddr, &profiles,&rep,soap);                // 获取媒体配置文件（主/辅码流配置信息）


    for (int i = 0;i < profile_cnt;i++)
    {
        ONVIF_GetStreamUri(DeviceXAddr, profiles[i].token, uri, sizeof(uri)); // 获取RTSP地址
        make_uri_withauth(uri, username, passwd, uri_auth, sizeof(uri_auth)); // 生成带认证信息的URI（有的IPC要求认证）
        printf("%s media channel %d %dx%d uri_auth:%s\n",rep.Profiles[i].Name,i, profiles[i].venc.Width,profiles[i].venc.Height,uri_auth);
    }


    if (NULL != veco_soap) {
        ONVIF_soap_delete(veco_soap);
    }
    if (NULL != vec_soap) {
        ONVIF_soap_delete(vec_soap);
    }
    if (NULL != soap) {
        ONVIF_soap_delete(soap);
    }

    if (NULL != profiles) {
        free(profiles);
        profiles = NULL;
    }
}
//发现整个网络的设备
int main(int argc, char **argv)
{
    setbuf(stdout,NULL); //or use:setvbuf(stdout,0,_IONBF,0);printf to debug window


    //get rtsp url
    //getmediainfo("http://192.168.21.202:580");
    //回调
    ONVIF_DetectDevice(cb_discovery);

    return 0;
}
